package main.java.org.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

// 游戏主类
public class ShootingGame extends JPanel implements KeyListener {
    public final static int WIDTH = 1800;
    public final static int HEIGHT = 1600;
    private final int PLAYER_SIZE = 40;
    private final int ENEMY_SIZE = 30;
    public final static int BULLET_SIZE = 5;

    private static int ENEMY_NUM = 5;

    private int level = 1; // 当前关卡

    private Player player;
    private ArrayList<Enemy> enemies;
    public static ArrayList<Bullet> bullets;
    private int score;
    private int health;
    private boolean gameRunning;

    // 游戏初始化
    public ShootingGame() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(Color.BLACK);
        setFocusable(true);
        addKeyListener(this);

        player = new Player(WIDTH / 2, HEIGHT - 100, PLAYER_SIZE);
        enemies = new ArrayList<>();
        bullets = new ArrayList<>();
        score = 0;
        health = 100000;
        gameRunning = true;

        spawnEnemies(5);
        startGameLoop();
    }

    // 生成敌人
    private void spawnEnemies(int num) {
        Random rand = new Random();
        for (int i = 0; i < num; i++) {
            int x = rand.nextInt(WIDTH - ENEMY_SIZE);
            int y = rand.nextInt(HEIGHT - ENEMY_SIZE);
            enemies.add(new Enemy(x, y, ENEMY_SIZE, level-1 ,level-1));
        }
    }

    // 游戏主循环
    private void startGameLoop() {
        Thread gameLoop = new Thread(() -> {
            while (gameRunning) {
                update();
                repaint();
                try {
                    Thread.sleep(16); // ~60 FPS
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        gameLoop.start();
    }

    // 游戏状态更新
    private void update() {
        player.move();
        for (Bullet bullet : bullets) {
            bullet.move();
        }
        checkCollisions();
        removeOutOfBoundsBullets();
        spawnEnemiesIfNeeded();
        moveEnemiesTowardsPlayer();
        checkPlayerHealth();
        checkNextLevel(); // 检查是否切换到下一关
    }

    // 检查进入下一关的条件
    private void checkNextLevel() {
        int nextLevelThreshold = 100 * (level); // 下一关的阈值
        if (score >= nextLevelThreshold) { // 检查玩家分数是否超过下一关的阈值
            level++; // 切换到下一关
            if (level <= 3) {
                JOptionPane.showMessageDialog(this, "恭喜进入下一关", "Game Over", JOptionPane.INFORMATION_MESSAGE);
                // 更新敌人数量和移动速度
                enemies.clear();
                ENEMY_NUM = 10;
                spawnEnemies(ENEMY_NUM); // 添加新的敌人
            } else {
                // 游戏结束
                gameOver(true);
            }
        }
    }

    // 检查碰撞
    private void checkCollisions() {
        Iterator<Enemy> enemyIterator = enemies.iterator();
        while (enemyIterator.hasNext()) {
            Enemy enemy = enemyIterator.next();
            Rectangle enemyRect = new Rectangle(enemy.getX(), enemy.getY(), enemy.getSize(), enemy.getSize());

            Iterator<Bullet> bulletIterator = bullets.iterator();
            while (bulletIterator.hasNext()) {
                Bullet bullet = bulletIterator.next();
                Rectangle bulletRect = new Rectangle(bullet.getX(), bullet.getY(), BULLET_SIZE, BULLET_SIZE);
                if (enemyRect.intersects(bulletRect)) {
                    score += 10;
                    bulletIterator.remove();
                    enemyIterator.remove();
                    break;
                }
            }

            Rectangle playerRect = new Rectangle(player.getX(), player.getY(), player.getSize(), player.getSize());
            if (enemyRect.intersects(playerRect)) {
                health -= 10;
                enemyIterator.remove();
                break;
            }
        }
    }



    // 移除越界的子弹
    private void removeOutOfBoundsBullets() {
        bullets.removeIf(bullet -> bullet.getX() < 0 || bullet.getX() > WIDTH || bullet.getY() < 0 || bullet.getY() > HEIGHT);
    }

    // 当敌人数量不足时生成新的敌人
    private void spawnEnemiesIfNeeded() {
        if (enemies.size() < 5) {
            spawnEnemies(ENEMY_NUM);
        }
    }

    // 移动敌人向玩家靠近
    private void moveEnemiesTowardsPlayer() {
        for (Enemy enemy : enemies) {
            enemy.moveTowards(player.getX(), player.getY());
        }
    }

    // 检查玩家生命值
    private void checkPlayerHealth() {
        if (health <= 0) {
            gameRunning = false;
            System.out.println("Game Over! Your score: " + score);
            gameOver(false); // 游戏失败
        }
    }

    // 绘制游戏界面
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        player.draw(g);
        for (Enemy enemy : enemies) {
            enemy.draw(g);
        }
        for (Bullet bullet : bullets) {
            bullet.draw(g);
        }
        g.setColor(Color.WHITE);
        g.drawString("Score: " + score, 20, 20);
        g.drawString("Health: " + health, 20, 40);
    }

    // 游戏结束
    private void gameOver(boolean win) {
        String message;
        if (win) {
            message = "You win! Your score: " + score;
        } else {
            message = "Game Over! Your score: " + score;
        }
        JOptionPane.showMessageDialog(this, message, "Game Over", JOptionPane.INFORMATION_MESSAGE);
        System.exit(0);
    }

    // 键盘按下事件处理
    @Override
    public void keyPressed(KeyEvent e) {
        player.keyPressed(e.getKeyCode());
    }

    // 键盘释放事件处理
    @Override
    public void keyReleased(KeyEvent e) {
        player.keyReleased(e.getKeyCode());
    }

    // 键盘输入事件处理
    @Override
    public void keyTyped(KeyEvent e) {}

    // 主方法，启动游戏
    public static void main(String[] args) {
        JFrame frame = new JFrame("Shooting Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.add(new ShootingGame());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}



